﻿// **************************************************
// 以下代码由代码生成器生成。
// 请不要修改该文件，以避免您的修改被代码生成器覆盖。
// 如需扩展方法，可新建文件，利用partial类特性来实现。
// **************************************************
using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Uow;
using Volo.Abp.Settings;
using Volo.Abp.Domain.Services;
using Volo.Abp.EventBus.Distributed;
using Joy.Erp.BasicArchives.Core.Events;
using Joy.Erp.BasicArchives.Core.UniqueCodes;

namespace {{namespace}}
{
    public partial class {{class_name}}Manager : DomainService
    {
        protected I{{class_name}}Repository {{class_name}}Repository => LazyServiceProvider.LazyGetRequiredService<I{{class_name}}Repository>();
        protected IDistributedEventBus DistributedEventBus => LazyServiceProvider.LazyGetRequiredService<IDistributedEventBus>();
        protected ISettingProvider SettingProvider => LazyServiceProvider.LazyGetRequiredService<ISettingProvider>();
        protected IUniqueCodeSetter UniqueCodeSetter => LazyServiceProvider.LazyGetRequiredService<IUniqueCodeSetter>();

        [UnitOfWork]
        public async Task<{{class_name}}> CreateAsync({{class_name}} entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            entity.SetId(GuidGenerator.Create());
            entity.TenantId = CurrentTenant.Id;

            var uniqueCodeConfigration = await SettingProvider.GetOrNullAsync($"UniqueCodeConfigration:{typeof({{class_name}}).FullName}");
            UniqueCodeSetter.SetCode(entity, uniqueCodeConfigration);

            await DistributedEventBus.PublishAsync(new EntityCreatingEto<{{class_name}}>(entity), false);
            return await {{class_name}}Repository.InsertAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task<{{class_name}}> UpdateAsync({{class_name}} entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            await DistributedEventBus.PublishAsync(new EntityUpdatingEto<{{class_name}}>(entity), false);
            return await {{class_name}}Repository.UpdateAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task DeleteAsync(Guid id, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            var entity = await {{class_name}}Repository.GetAsync(id);

            await DistributedEventBus.PublishAsync(new EntityDeletingEto<{{class_name}}>(entity), false);
            await {{class_name}}Repository.DeleteAsync(entity, autoSave, cancellationToken);
        }
    }
}
